<?php

namespace App\Http\Controllers\Admin\Administration;

use App\Exports\OfficeExport;
use App\Http\Controllers\Controller;
use App\Http\Requests\administration\OfficeRequest;
use App\Imports\FixedImport;
use App\Imports\OfficeImport;
use App\Imports\OfficeRecordImport;
use App\Models\administration\FixedModel;
use App\Models\administration\OfficeModel;
use App\Models\administration\RecordModel;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Maatwebsite\Excel\Facades\Excel;

class Office extends Controller
{
    use OfficeRequest;

    /**
     * Notes:列表
     * User: xiangzi
     * Date: 2024/9/5
     * Time: 14:35
     * @return \Illuminate\Http\JsonResponse
     */
    public function list(Request $request) {
        $page = $request->input('page', 1);
        $limit = $request->input('limit', 20);
        $name = $request->input('name', '');
        $buy_start = $request->input('buy_start', '');
        $buy_end = $request->input('buy_end', '');

        $query = OfficeModel::query()->with('create_admin');

        if($name){
            $query->where('name', 'like', '%'.$name.'%');
        }

//        if($buy_start && $buy_end){
//            $query = $query->whereBetween('buy_time', [$buy_start, $buy_end]);
//        }

        $total = $query->count('id');
        $items = $query
            ->offset(($page-1) * $limit)
            ->limit($limit)
            ->orderBy('id', 'desc')
            ->get();

        $list = $items->map(function($item) {
            $res = [
                'id' => $item->id,
                'code' => $item->code,
                'name' => $item->name,
                'spe' => $item->spe,
                'model' => $item->model,
                'unit' => $item->unit,
                'color' => $item->color,
                'total_purchase_number' => $item->total_purchase_number,
                'stock_number' => $item->stock_number,
                'created_at' => $item->created_at->toDateTimeString(),
                'create_user' => $item->create_admin ? $item->create_admin->staff->name : '',
            ];
            return $res;
        });

        return $this->success(['list' => $list, 'total' => $total]);
    }

    /**
     * Notes:添加
     * User: xiangzi
     * Date: 2024/9/5
     * Time: 14:35
     * @return \Illuminate\Http\JsonResponse
     */
    public function add(Request $request){
        $auth = $request->get('auth');
        $params = $request->all();

        $check_res = self::add_check($params);
        if($check_res->faild){
            return $this->error($check_res->err);
        }

        $find = OfficeModel::where('name', $params['name'])->first();
        if($find){
            return $this->error('名称已存在');
        }

        $model = new OfficeModel();
        $model->code = getCode('assets', "EML");
        $model->name = $params['name'];
        $model->spe = isset($params['spe']) ? $params['spe'] : '';
        $model->model = isset($params['model']) ? $params['model'] : '';
        $model->unit = $params['unit'];
        $model->color = $params['color'];
        $model->created_admin_id = $auth->id;
        $model->save();

        return $this->success();
    }

    public function update(Request $request, $id){
        $params = $request->all();

        $check_res = self::add_check($params);
        if($check_res->faild){
            return $this->error($check_res->err);
        }

        $model = OfficeModel::find($id);
        if (!$model) {
            return $this->error('数据不存在');
        }

        if($model->name != $params['name']){
            $find = OfficeModel::where('name', $params['name'])->first();
            if($find){
                return $this->error('名称已存在');
            }
        }

        $model->name = $params['name'];
        $model->spe = isset($params['spe']) ? $params['spe'] : '';
        $model->model = isset($params['model']) ? $params['model'] : '';
        $model->unit = $params['unit'];
        $model->color = $params['color'];
        $model->save();

        return $this->success();
    }


    public function delete(int $id){
        $model = OfficeModel::find($id);
        if(!$model) {
            return $this->error('记录不存在');
        }
        $model->delete();
        return $this->success();
    }

    public function delete_batch(Request $request)
    {
        $ids = $request->input('ids', []);
        if(empty($ids)){
            return $this->error('请选择要删除的数据');
        }
        OfficeModel::destroy($ids);
        return $this->success();

    }

    public function export(Request $request)
    {
        $ids = $request->input('ids', []);
        if(empty($ids)){
            return $this->error('请选择要导出的数据');
        }

        $query = OfficeModel::query();
        $query->whereIn('id', $ids);
        $items = $query
            ->orderBy('id', 'desc')
            ->get();


        $list = $items->map(function($item) {
            $res = [
                'type' => $item->type,
                'code' => $item->code,
                'name' => $item->name,
                'spe' => $item->spe,
                'model' => $item->model,
                'color' => $item->color,
                'unit' => $item->volume,
                'number' => $item->number,
                'price' => $item->price,
                'last_month_number' => $item->last_month_number,
                'last_month_amount' => $item->last_month_amount,
                'enter_date' => $item->enter_date,
                'enter_number' => $item->enter_number,
                'enter_amount' => $item->enter_amount,
                'out_date' => $item->out_date,
                'out_number' => $item->out_number,
                'out_amount' => $item->out_amount,
                'save_number' => $item->save_number,
                'save_amount' => $item->save_amount,
                'remark' => $item->remark,
            ];
            return $res;
        });

        $file_name = '办公物品-'.date('Ymd').'.xlsx';
        return Excel::download(new OfficeExport($list), $file_name);
    }

    public function import(Request $request)
    {
        $auth = $request->get('auth');
        $file = $request->file('file');
        if(!$file){
            return $this->error('请选择文件');
        }

        $import = new OfficeImport();
        Excel::import($import, $file);


        $res = $import->get_result();

        if(isset($res->error) && $res->error){
            return $this->error(implode(',', $res->error));
        }

        $lines = $res->lines;

        DB::beginTransaction();
        try {
            foreach ($lines as $line){
                $office = OfficeModel::where('name', $line['name'])->first();

                if(!$office){
                    $office  = new OfficeModel();
                }

                $office->type = $line['type'];
                $office->name = $line['name'];
                $office->code = $line['code'];
                $office->unit = $line['unit'];
                $office->spe = $line['spe'];
                $office->model = $line['model'];
                $office->color = $line['color'];
                $office->stock_number = $line['number'];
                $office->price = $line['price'];
                $office->last_month_number = $line['last_month_number'];
                $office->last_month_amount = $line['last_month_amount'];
                $office->enter_date = $line['enter_date'];
                $office->enter_number = $line['enter_number'];
                $office->enter_amount = $line['enter_amount'];
                $office->out_date = $line['out_date'];
                $office->out_number = $line['out_number'];
                $office->out_amount = $line['out_amount'];
                $office->save_number = $line['save_number'];
                $office->save_amount = $line['save_amount'];
                $office->remark = $line['remark'];
                $office->created_admin_id = $auth->id;
                $office->save();

                $office->total_purchase_number = $office->total_purchase_number ? $office->total_purchase_number + $line['number'] : $line['number'];
                $office->stock_number = $office->stock_number ? $office->stock_number + $line['number'] : $line['number'];
                $office->save();

            }
            DB::commit();
        }catch (\Exception $e){
            DB::rollBack();
            return $this->error($e->getMessage());
        }

        return  $this->success();
    }



}
